package fun.shuofeng.juc.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 朔风
 * @date 2024-01-28 16:13
 */
public class ThreadDemoShare {
    public static void main(String[] args) {
        Share share = new Share();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "AA").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "BB").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "CC").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "DD").start();

    }
}

class Share {
    private int number = 0;

    // 创建Lock锁
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    /**
     * +1
     */
    public void incr() throws InterruptedException {
        // 上锁
        lock.lock();
        try {
            while (number != 0) {
                // 等待，直到被唤醒
                condition.await();
            }
            // 干活
            number++;
            System.out.println(Thread.currentThread().getName() + "::" + number);
            // 通知，唤醒所有线程
            condition.signalAll();
        } finally {
            // 释放锁
            lock.unlock();
        }
    }

    /**
     * -1
     */
    public void decr() throws InterruptedException {
        // 上锁
        lock.lock();
        try {
            while (number != 1) {
                condition.await();
            }
            // 干活
            number--;
            System.out.println(Thread.currentThread().getName() + "::" + number);
            // 通知
            condition.signalAll();
        } finally {
            // 释放锁
            lock.unlock();
        }
    }

}
